<template>
	<view class="select-city-container">
		<u-sticky offset-top="0" h5-nav-height="0" bg-color="transparent" :enable="enable">
		    <u-navbar
				title="选择城市"
				titleColor="#FFF"
		        :border-bottom="false"
		        :is-fixed="false"
		        custom-class="nav-bg"
				:background="{background: '#116568'}"
				back-icon-color="#FFF"
		    > 
		    </u-navbar>
		</u-sticky>
		<view class="select-city-box">
			<view class="title">当前所在城市</view>
			<view class="city-list">
				<view class="city-item"  v-if="cityName">{{cityName}}</view>
				<view class="city-item" @tap="getCurrentCity" v-else>点击授权</view>
			</view>
			<view class="title">当前所在城市</view>
			<view class="city-list">
				<view class="city-item" v-for="(item,index) in cityList" :key="index" @tap="handleChangeCity(item)">{{item.name}}</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { getCityByLocation, getOpenCity } from '@/api/store'
	import Cache from "@/utils/cache";
	import { CITY_DATA, CURRENT_LOCATION, CITY_CODE, CITY_NAME } from '@/config/cachekey'
	
	export default {
		data(){
			return {
				cityList: [],
				cityData: {},
				currentLocation: {},
				cityName: ''
			}
		},
		onLoad(options) {
			console.log('options', options)
			console.log('Cache.get(CITY_DATA)', Cache.get(CITY_DATA))
			if(Cache.get(CITY_DATA)){
				this.cityData = Cache.get(CITY_DATA)
			}
			this.getOpenCityFun()
		},
		onShow(){
			console.log('Cache.get(CITY_NAME)', Cache.get(CITY_NAME))
			if(Cache.get(CITY_NAME)){ // 城市名字
				this.cityName = Cache.get(CITY_NAME)
				console.log('this.cityName', this.cityName)
			}
		},
		methods: {
			handleChangeCity(item){
				console.log('item', item)
				let {id, name} = item
				Cache.set(CITY_CODE, id)
				Cache.set(CITY_NAME, name)
				this.cityName = name
				uni.switchTab({
					url: `/pages/index/index`
				})
			},
			// 授权位置信息
			getCurrentCity(fn) {
				uni.getSetting({
					success: res => {
						if (res.authSetting && res.authSetting.hasOwnProperty("scope.userLocation")) {
							if (res.authSetting["scope.userLocation"]) {
								this.getLocation(fn)
							} else {
								uni.hideLoading()
								uni.showModal({
									title: '提示',
									content: '请重新授权获取您的地理位置，否则部分功能将无法使用',
									success: (res) => {
										if (res.confirm) {
											uni.openSetting({
												success: () => this.getLocation(fn)
											})
										} else {
											uni.showToast({
												title: '请授权获取您的地理位置，否则部分功能将无法使用',
												icon: 'none',
												duration: 2000
											})
										}
									},
									fail: (res) => {
										uni.showToast({
											title: '位置获取失败',
											icon: "none",
											duration: 2000
										})
									}
								})
							}
						} else {
							this.getLocation(fn)
						}
					}
				})
			},
			// 获取当前位置坐标
			getLocation (fn) {
			      let that = this
			      // 获取用户是否开启 授权获取当前的地理位置、速度的权限。
			      uni.getSetting({
			        success (res) {
			          console.log(res)
			
			          // 如果没有授权
			          if (!res.authSetting['scope.userLocation']) {
			            // 则拉起授权窗口
			            uni.authorize({
			              scope: 'scope.userLocation',
			              success () {
			                //点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
			                uni.getLocation({
			                  type: 'wgs84',
							  geocode: true,//设置该参数为true可直接获取经纬度及城市信息
			                  success: function (res) {
								console.log('允许授权res', res)
			                    that.x = res.longitude
			                    that.y = res.latitude
			                    console.log(res)
			                    console.log('当前位置的经度：' + res.longitude)
			                    console.log('当前位置的纬度：' + res.latitude)
								that.currentLocation = res
								
								Cache.set(CURRENT_LOCATION, res)
								that.getCurCity()
								
			                    // uni.showToast({
			                    //   title: '当前位置的经纬度：' + res.longitude + ',' + res.latitude,
			                    //   icon: 'success',
			                    //   mask: true
			                    // })
			                  }, fail (error) {
			                    console.log('失败', error)
								uni.showToast({
									title: error.errMsg,
									icon: 'error',
									mask: true
								})
			                  }
			                })
			              },
			              fail (error) {
			                //点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
			                console.log('拒绝授权', error)
			
			                uni.showModal({
			                  title: '提示',
			                  content: '若点击不授权，将无法使用位置功能',
			                  cancelText: '不授权',
			                  cancelColor: '#999',
			                  confirmText: '授权',
			                  confirmColor: '#f94218',
			                  success (res) {
			                    console.log(res)
			                    if (res.confirm) {
			                      // 选择弹框内授权
			                      uni.openSetting({
			                        success (res) {
			                          console.log(res.authSetting)
			                        }
			                      })
			                    } else if (res.cancel) {
			                      // 选择弹框内 不授权
			                      console.log('用户点击不授权')
			                    }
			                  }
			                })
			              }
			            })
			          } else {
			            // 有权限则直接获取
			            uni.getLocation({
			              type: 'wgs84',
						  geocode: true,//设置该参数为true可直接获取经纬度及城市信息
			              success: function (res) {
			                that.x = res.longitude
			                that.y = res.latitude
			                console.log(res)
			                console.log('当前位置的经度：' + res.longitude)
			                console.log('当前位置的纬度：' + res.latitude)
							console.log('允许授权res', res)
							that.currentLocation = res
							Cache.set(CURRENT_LOCATION, res)
							that.getCurCity()
			                // uni.showToast({
			                //   title: '当前位置的经纬度：' + res.longitude + ',' + res.latitude,
			                //   icon: 'success',
			                //   mask: true
			                // })
			              }, fail (error) {
			                uni.showToast({
			                  title: '请勿频繁调用！',
			                  icon: 'none',
			                })
			                console.log('失败', error)
			              }
			            })
			          }
			        }
			      })
			},
			async getCurCity(){
				console.log('this.currentLocation', this.currentLocation)
				let { longitude, latitude } = this.currentLocation
				let params = {
					lng: longitude,
					lat: latitude
				}
				let res = await getCityByLocation(params)
				// console.log('getCurCity--res', res)
				console.log('根据当前经纬度返回的城市信息：', res)
				this.cityData = res.data;
				console.log('this.cityData', this.cityData)
				Cache.set(CITY_DATA, res.data)
				Cache.set(CITY_CODE, res.data.city_code)
				Cache.set(CITY_NAME, res.data.city)
				this.cityName = res.data.city
			},
			getOpenCityFun(){
				getOpenCity().then((res) => {
					if(res.code == 1){
						this.cityList = res.data;
						console.log('this.cityList', this.cityList)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.select-city-container{
		min-height: 100vh;
		background: #FFF;
		.select-city-box{
			padding: 0 32rpx 32rpx;
			.title{
				font-size: 28rpx;
				color: #545454;
				margin-top: 32rpx;
			}
			.city-list{
				 display: flex;
				 flex-wrap: wrap;
				 justify-content: space-between;
			}
			.city-item{
				width: 200rpx;
				height: 76rpx;
				line-height: 76rpx;
				text-align: center;
				margin-top: 30rpx;
				font-size: 30rpx;
				color: #040404;
				border: 1rpx solid #cdcdcd;
				
			}
		}
	}
</style>